/*
 * @Author: Kingsley 
 * @Date: 2018-10-21 18:10:19 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2018-10-27 15:36:44
 * 收货地址 
 */
<template>
  <div class="address w">
    <el-card class="box-card">
      <div class="address-con" v-loading="pageData.loading">

        <div class="address-item " v-bind:class="{active:address.id == pageData.selectedAddresId}" v-for="(address,index) in resData.addresList" :key="index" @click="clickAddress(address.id)">
          <div class="address-title">{{address.receiverProvince}}{{address.receiverCity}}({{address.receiverName}})收</div>
          <div class="address-detail">{{address.receiverAddress}}</div>
          <div class="address-tel">tel:{{address.receiverPhone}}</div>
          <div class="address-opera">
            <span class="link address-update" @click="editAddress(address)">编辑</span>
            <span class="link address-delete" @click="deleteAddress(address.id)">删除</span>
          </div>
        </div>

        <div class="address-add" @click="pageData.dialogVisible = true">
          <div class="address-new">
            <i class="fa fa-plus"></i>
            <div class="text">新增收回地址</div>
          </div>
        </div>

      </div>
    </el-card>

    <div class="add-address-pop">
      <el-dialog title="收货地址" :visible.sync="pageData.dialogVisible">
        <el-form :model="pageData.fromData" :rules="pageData.fromRules" ref="addressFrom">

          <el-form-item label="收件人" label-width="120px" prop="receiverName">
            <el-input v-model="pageData.fromData.receiverName" autocomplete="on" placeholder="请填写收件人名称"></el-input>
          </el-form-item>

          <el-form-item label="省份" label-width="120px" prop="receiverProvince">
            <el-select v-model="pageData.fromData.receiverProvince" placeholder="请选择省份" autocomplete="address-level1">
              <el-option-group v-for="group in pageData.provinceReonmentOption" :key="group.label" :label="group.label">
                <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" autocomplete="on">
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>

          <el-form-item label="城市" label-width="120px" prop="receiverCity">
            <el-select v-model="pageData.fromData.receiverCity" placeholder="请选择城市" autocomplete="address-leve2">
              <el-option v-for="item in pageData.cityOption" :key="item.value" :label="item.value" :value="item.value" autocomplete="on">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址" label-width="120px" prop="receiverAddress">
            <el-input v-model="pageData.fromData.receiverAddress" autocomplete="on" placeholder="请填写详细地址（精确到门牌号）"></el-input>
          </el-form-item>

          <el-form-item label="手机号" label-width="120px" prop="receiverPhone">
            <el-input v-model="pageData.fromData.receiverPhone" autocomplete="on" placeholder="请填写收件人联系号码"></el-input>
          </el-form-item>

          <el-form-item label="邮政编码" label-width="120px">
            <el-input v-model="pageData.fromData.receiverZip" autocomplete="on" placeholder="请填写邮政编码"></el-input>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="pageData.dialogVisible = false">取 消</el-button>
          <el-button v-if="pageData.isEditAddress" type="primary" @click="editAddressForm('addressFrom')">编辑</el-button>
          <el-button v-else type="primary" @click="submitAddressForm('addressFrom')">保存</el-button>
        </div>

      </el-dialog>
    </div>
  </div>
</template>

<script>
import _city from "@/utils/city/cities";
import Tips from "@/utils/tipsUtil";
const _tips = new Tips();
import Address from "@/service/address-service";
import RulesUtil from "@/utils/rulesUtil";
const _regular = new RulesUtil();
const _address = new Address();
export default {
  data() {
    //自定义的验证规则 电话号码的验证
    let validatePhone = (rule, value, callback) => {
      let result = _regular.validate(value, "phone");
      if (result) {
        callback(new Error(result));
      } else {
        callback();
      }
    };

    return {
      pageData: {
        selectedAddresId: null, //选中的收货地址id
        loading: true,
        dialogVisible: false,
        addressDelete: false,
        isEditAddress: false,
        provinceReonmentOption: [
          {
            label: "推荐省份",
            options: [
              {
                value: "北京",
                label: "北京"
              },
              {
                value: "上海",
                label: "上海"
              },
              {
                value: "广东省",
                label: "广东省"
              }
            ]
          },
          {
            label: "省份",
            options: []
          }
        ],
        provinceOption: [],
        cityOption: [],
        fromData: {
          receiverName: "",
          receiverPhone: "",
          receiverProvince: "",
          receiverCity: "",
          receiverAddress: "",
          receiverZip: "",
          id: ""
        },
        fromRules: {
          receiverName: [
            { required: true, message: "请输入收件人名称", trigger: "blur" }
          ],
          receiverProvince: [
            { required: true, message: "请选择省份", trigger: "blur" }
          ],
          receiverCity: [
            { required: true, message: "请选择城市", trigger: "blur" }
          ],
          receiverAddress: [
            { required: true, message: "请输入收件的详细地址", trigger: "blur" }
          ],
          receiverPhone: [{ validator: validatePhone, trigger: "blur" }]
        }
      },

      /**
       *
       */
      resData: {
        addresList: []
      }
    };
  },
  mounted() {
    this.init();
    this.initAddressList();
  },
  watch: {
    "pageData.fromData.receiverProvince"(newValue, oldValue) {
      this.loadReceiverCity(newValue);
    }
  },
  components: {},
  methods: {
    /**
     * 初始化加载省份信息
     */
    init() {
      const vue = this;
      let provinces = [];

      provinces = _city.getProvinces();
      for (let i = 0, iLength = provinces.length; i < iLength; i++) {
        vue.pageData.provinceOption.push({
          value: provinces[i],
          label: provinces[i]
        });
      }
      vue.pageData.provinceReonmentOption[1].options =
        vue.pageData.provinceOption;
    },

    /**
     * 初始化加载收货地址列表信息
     */
    initAddressList() {
      const vue = this;
      _address.addresList().then(
        res => {
          vue.resData.addresList = res.data.list;
          //关闭加载图标
          vue.pageData.loading = false;
        },
        err => {
          _tips.notifyTips(vue, err.msg);
        }
      );
    },

    /**
     * 加载省份对应的城市
     */
    loadReceiverCity(provinceName) {
      const vue = this;
      if (provinceName) {
        //原本可能会有缓存信息，先置空
        vue.pageData.cityOption = [];
        let cities = _city.getCities(provinceName);
        for (let i = 0, iLength = cities.length; i < iLength; i++) {
          vue.pageData.cityOption.push({
            value: cities[i],
            label: cities[i]
          });
        }
      } else {
        //todo
      }
    },

    /**
     *提交新增收货地址的表单
     */
    submitAddressForm(formName) {
      const vue = this;
      vue.$refs[formName].validate(valid => {
        if (valid) {
          _address.addAddress(vue.pageData.fromData).then(
            res => {
              //显示加载图片
              vue.pageData.loading = true;
              //隐藏表单弹出框
              vue.pageData.dialogVisible = false;
              vue.initAddressList();
            },
            err => {
              _tips.notifyTips(vue, err.msg);
            }
          );
        } else {
          _tips.notifyTips(vue, "填写表单有误");
          return false;
        }
      });
    },

    /**
     * 删除点击的收货地址
     */
    deleteAddress(id) {
      const vue = this;
      const tipsData = {
        msg: "三思~确定删除该条收货地址记录吗？"
      };
      _tips.confirmTips(
        vue,
        tipsData,
        //按下确定的回调函数
        () => {
          _address.deleteAddress(id).then(
            res => {
              //显示加载图片
              vue.pageData.loading = true;
              vue.initAddressList();
            },
            res => {
              _tips.notifyTips(vue, "填写表单有误");
            }
          );
        },
        //按下取消的回调函数
        () => {}
      );
    },

    editAddress(address) {
      const vue = this;
      vue.pageData.fromData.receiverAddress = address.receiverAddress;
      vue.pageData.fromData.receiverCity = address.receiverCity;
      vue.pageData.fromData.receiverName = address.receiverName;
      vue.pageData.fromData.receiverPhone = address.receiverPhone;
      vue.pageData.fromData.receiverProvince = address.receiverProvince;
      vue.pageData.fromData.receiverZip = address.receiverZip;
      vue.pageData.fromData.id = address.id;
      vue.pageData.dialogVisible = true;
      vue.pageData.isEditAddress = true;
    },

    editAddressForm(formName) {
      const vue = this;
      vue.$refs[formName].validate(valid => {
        if (valid) {
          _address.updateAddress(vue.pageData.fromData).then(
            res => {
              //显示加载图片
              vue.pageData.loading = true;
              //隐藏表单弹出框
              vue.pageData.dialogVisible = false;
              vue.initAddressList();
            },
            err => {
              _tips.notifyTips(vue, err.msg);
            }
          );
        } else {
          _tips.notifyTips(vue, "填写表单有误");
          return false;
        }
      });
    },

    /**
     *点击收货地址
     */
    clickAddress(id) {
      /**
       * 第一个参数：clickChildAddr是父组件监听的方法；
       * 第二参数：id 是子组件向父组件传递的值
       */
      this.pageData.selectedAddresId = id; // 缓存选中收货地址id,显示active样式
      this.$emit("clickChildAddr", id);
    }
  }
};
</script>

<style scoped lang="scss">
.address-con {
  .address-item,
  .address-add {
    margin: 20px 20px 20px 5px;
    width: 220px;
    padding: 2px 8px;
    float: left;
    border: 2px dashed #ccc;
    cursor: pointer;
  }
  //地址列表和新增地址的背景色
  .address-item:hover,
  .address-add:hover {
    background: #fafafa;
  }
  .address-item.active {
    border: 2px dashed #409eff;
  }
  .address-item {
    .address-title {
      color: #666;
      height: 25px;
      line-height: 25px;
      overflow: hidden;
      padding: 2px 0;
      border-bottom: 1px solid #ddd;
      text-align: center;
    }
    .address-detail {
      margin-top: 5px;
      padding: 2px 0 0 2px;
      height: 20px;
      line-height: 20px;
      overflow: hidden;
      color: #666;
      text-align: left;
    }
    .address-tel {
      text-align: left;
      padding: 2px 0 0 2px;
      overflow: hidden;
    }
    .address-opera {
      text-align: right;
      visibility: hidden;
    }
    .address-opera {
      .link {
        margin-right: 5px;
      }
    }
  }
  .address-item:hover .address-opera {
    visibility: visible;
  }

  //新增收货地址
  .address-add {
    .address-new {
      padding: 14px 0;
      text-align: center;
      color: #ccc;
      .fa {
        font-size: 50px;
        line-height: 50px;
      }
      .text {
        font-size: 12px;
      }
    }
    .address-new:hover {
      color: #409eff;
    }
  }
}
//收货地址弹出框
.add-address-pop {
  text-align: left;
}
</style>
